<script setup>
import { ref } from 'vue'
import DataTable from '@/components/DataTable.vue'
import TagEditDialog from '@/components/TagEditDialog.vue'
import { getTags, createTag, updateTag, deleteTag, deleteBatch } from '@/api/tags.js'
import { useMessageStore } from '@/stores/MessageStore.js'

const headers = [
  { title: '标签名', key: 'name' },
  { title: '标签创建者', key: 'createdBy' },
  { title: '标签描述', key: 'description' },
  { title: '标签创建时间', key: 'createdAt' },
  { title: '标签更新时间', key: 'updatedAt' },
  { title: '操作', key: 'actions', sortable: false },
]

const searchQuery = ref('')

const tagsApi = {
  fetch: (params) => getTags({ ...params, search: searchQuery.value }),
  create: createTag,
  delete: deleteTag,
  deleteBatch: deleteBatch,
}

const refreshTrigger = ref(0)
const tableRef = ref(null)
const showDialog = ref(false)
const editingTag = ref(null)

const openEdit = (row) => {
  editingTag.value = row
  showDialog.value = true
}

const handleCreate = async (formData) => {
  try {
    if (editingTag.value) {
      // 更新标签
      await updateTag(formData)
    } else {
      // 创建新标签
      await createTag(formData)
    }
    refreshTrigger.value++
  } catch (error) {
    console.error('保存标签失败:', error)
  }
}

const handleDelete = async (row) => {
  if (row) {
    try {
      await deleteTag(row.id)
      refreshTrigger.value++
    } catch (error) {
      console.error('删除标签失败:', error)
    }
  } else {
    useMessageStore().trigger('该项不存在', 'error')
  }
}

const handleSearch = () => {
  refreshTrigger.value++
}
</script>

<template>
  <h1>标签管理</h1>
  <v-spacer />
  <v-card-text>
    <v-row>
      <v-col cols="12" sm="6" md="4">
        <v-text-field
          v-model="searchQuery"
          label="搜索标签"
          prepend-inner-icon="mdi-magnify"
          variant="outlined"
          clearable
          @keyup.enter="handleSearch"
          @click:clear="handleSearch"
        />
      </v-col>
    </v-row>
    <DataTable
      ref="tableRef"
      :headers="headers"
      :api="tagsApi"
      :refresh-trigger="refreshTrigger"
      @edit="openEdit"
      @create="openEdit(null)"
      @delete="handleDelete"
    />
  </v-card-text>

  <TagEditDialog v-model="showDialog" :tag="editingTag" @submit="handleCreate" />
</template>
